//
//  MLBaseNavigationController.swift
//  SinaWeibo
//
//  Created by 李亮亮 on 16/4/8.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit

class MLBaseNavigationController: UINavigationController,UIGestureRecognizerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // 设置手势代理
        self.interactivePopGestureRecognizer?.delegate = self
        // 设置导航条的北京图片
        navigationBar.setBackgroundImage(UIImage(named: "navbarbackimaeg"), forBarMetrics: .Default)
    }
    
    // MARK: - 手势将要开始的协议代理方法
    // 协议方法返回值是 Bool  如果返回true就可以正常工作, 如果返回false手势就会失效
    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        
//        if childViewControllers.count == 1 {
//            return false
//        }
//        return true
        return childViewControllers.count != 1
    }
    
    
    // MARK: - 重写push方法
    // 重写了不 super
    // 根视图无法添加 -> UINavigationController(rootViewController:XXX)
    override func pushViewController(viewController: UIViewController, animated: Bool) {
        // 设置颜色,页面跳转的时候会有颜色切换导致的卡顿
        let value: CGFloat = 237 / 255.0
        viewController.view.backgroundColor = UIColor(red: value, green: value, blue: value, alpha: 1.0)
        
        // 设置viewController的leftItem
        if childViewControllers.count > 0 {
            var backTitle = "返回"
            
            if childViewControllers.count == 1 {
                backTitle = childViewControllers.first?.title ?? ""
            }
            
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: backTitle, imageName: "navigationbar_back_withtext", target: self, action: #selector(MLBaseNavigationController.back))
            
            // 隐藏底部的TabBar
            viewController.hidesBottomBarWhenPushed = true

        }
        
        // 必须要最后调用
        super.pushViewController(viewController, animated: animated)

    }
    
    @objc private func back() {
        self.popViewControllerAnimated(true)
    }
    
    
    
}
